<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="8">
          <a-form-item label="送样单位" v-bind="validateInfos.partName">
            <a-input v-model:value="formData.partName" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="报废名称" v-bind="validateInfos.discardName">
            <a-input v-model:value="formData.discardName" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="送样时间" v-bind="validateInfos.date">
            <a-date-picker v-model:value="formData.date" value-format="YYYY-MM-DD" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="送样人" v-bind="validateInfos.deliverPerson">
            <a-input v-model:value="formData.deliverPerson" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="收样人" v-bind="validateInfos.receivePerson">
            <a-input v-model:value="formData.receivePerson" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="存放地点" v-bind="validateInfos.savePlace">
            <a-input v-model:value="formData.savePlace" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-input v-model:value="formData.remark" :disabled="disabled"
            style="width: 850px; border-radius: 4px 4px 4px 4px; opacity: 1; border: 0.5px solid #DDDDDD ;"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 插入表格 -->
      <BasicTable @register="registerTable" :rowSelection="rowSelection" :pagination="false" :dataSource="chemicalList"
        :disabled="disabled">
        插槽:table标题
        <template #tableTitle>
          <a-button type="primary" preIcon="ant-design:plus-outlined" @click="selectAddChemical">添加标准物质</a-button>
          <template v-if="selectedRowKeys.length > 0">
            <a-dropdown>
              <template #overlay>
              </template>
              <a-button>
                <span>批量操作 </span>
                <icon icon="akar-icons:chevron-down" />
              </a-button>
            </a-dropdown>
          </template>
        </template>
        插槽：行内操作按钮
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
    </a-form>
  </a-spin>
  <!-- 插入表格对应model -->
  <ChemicalSelectModal rowKey="id" @register="registerSelChemicalModal" @getSelectResult="onSelectChemicalOk" style="height: 40px;overflow: auto;"/>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../LabChemicalDiscard.api';
import { Form } from 'ant-design-vue';
import ChemicalSelectModal from '../../chemical/standard/components/ChemicalSelectModal.vue';
import { useModal } from '/@/components/Modal/index';
import { useListPage } from '/@/hooks/system/useListPage';
import { ActionItem, BasicTable, TableAction } from '/@/components/Table/index';

import {discardColumns} from '../../chemical_discard_describe/LabChemicalDiscardDescribe.data';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  partName: '',
  discardName: '',
  date: '',
  deliverPerson: '',
  receivePerson: '',
  savePlace: '',
  remark: '',
});
// const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {
};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});
const { tableContext, createMessage } = useListPage({
  tableProps: {
    columns: discardColumns,
    canResize: false,
    useSearchForm: false,
    formConfig: {
      // baseColProps: adaptiveColProps,
      labelAlign: 'left',
      labelCol: {
        xs: 24,
        sm: 24,
        md: 24,
        lg: 9,
        xl: 7,
        xxl: 5,
      },
      wrapperCol: {},

    },
    // 请求之前对参数做处理
    beforeFetch(params) {
      // params.depId = departId.value;
    },
  },
});

// 注册 ListTable
const [registerTable, { reload, setProps, setLoading, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext;
const [registerSelChemicalModal, selChemicalModal] = useModal();


// 选择添加标准物质
function selectAddChemical() {
  selChemicalModal.openModal();
}
/**
 * 新增
 */
function add() {
  chemicalList.value = [];
  // edit({});
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, {});
  });
}

/**
 * 编辑
 */
async function edit(record) {
  chemicalList.value = await defHttp.get({ url: "/chemicalDiscard/labChemicalDiscardDescribe/queryList?discardId=" + record.id })
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, record);
  });
}
/**
* 操作栏
*/
function getTableAction(record): ActionItem[] {
  return [
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        width: 155,
        confirm: handleDelete.bind(null, record),
      }
    }
  ];
}
/**
  * 删除事件
  * 这里的删除是假删除
  */
async function handleDelete(record) {
  console.log("record.id", record.id);
  chemicalList.value = chemicalList.value.filter((chemical) => chemical.id !== record.id);
}

const chemicalList = ref();

async function onSelectChemicalOk( selectRows) {
  chemicalList.value = selectRows.value;//后端查出的标物信息
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }

  for (let i = 0; i < chemicalList.value.length; i++) {
    chemicalList.value[i].chemicalId = chemicalList.value[i].id;
    chemicalList.value[i].id = "";
  }
  console.log("chemicalList.value后", chemicalList.value);

  const target = JSON.parse(JSON.stringify(chemicalList.value));

  model.listDiscard = target;
  console.log("model-now", model);
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
